import {
  _decorator,
  Component,
  Node,
  UITransform,
  Sprite,
  Animation,
  SpriteFrame,
  AnimationClip,
  animation,
  utils,
} from 'cc'
const { ccclass, property } = _decorator

import {  TILE_WIDTH, TILE_HEIGHT } from '../Tile/TileMapManager'

// 引入事件中心
import EventManager from '../../Runtime/EventManager'
import DataManager from '../../Runtime/DataManager'

// 实体类型
import { EntityManager } from '../../Base/EntityManager'

// 状态机
import { BurstsStateMchine } from './BurstsStateMchine'

// 状态机类型
import { PLAYER_STATE_TYPE_ENUM, DIRECTION } from '../../Enums'



@ccclass('BurstsManager')
export class BurstsManager extends EntityManager {
  // id: string
  async init(pramers) {

    // 初始化状态机
    this.fsm = this.addComponent(BurstsStateMchine)
    await this.fsm.init()

    // 传入默认值
    super.init(pramers)

    // 设置大小
   const transform = this.getComponent(UITransform)
   transform.setContentSize(TILE_WIDTH, TILE_HEIGHT)

    // 注册事件
    EventManager.Instance.on('PLAYER_MOVE_END', this.judgeAttack, this)
  }

  onDestroy(): void {
    super.onDestroy()
    // 移除
    EventManager.Instance.off('PLAYER_MOVE_END', this.judgeAttack)
  }

  // 每帧更新
  update() {
    this.node.setPosition(this.x * TILE_WIDTH , -this.y * TILE_HEIGHT)
  }

  // 判断是否进行攻击
  judgeAttack() {
    const player = DataManager.Instance.player
    if (!player || this.state === PLAYER_STATE_TYPE_ENUM.DEATH) {
      return
    }

    const { targetX: playerX, targetY: playerY, state: playerState } = player
    const { x, y } = this

    // 判断不能攻击死亡的玩家
    if([PLAYER_STATE_TYPE_ENUM.DEATH, PLAYER_STATE_TYPE_ENUM.AIR_DEATH].indexOf(playerState) > -1) {
      return
    }

    // 判断是否可以攻击
    if (playerX === x  && playerY === y  && this.state === PLAYER_STATE_TYPE_ENUM.IDLE) {
      this.state = PLAYER_STATE_TYPE_ENUM.ATTACK
    } else if(this.state === PLAYER_STATE_TYPE_ENUM.ATTACK) {
      this.state = PLAYER_STATE_TYPE_ENUM.DEATH
      EventManager.Instance.emit('SHAKE', DIRECTION.BOTTOM)

      // 如果玩家在上面，直接死亡
      if(playerX === x  && playerY === y ) {
        EventManager.Instance.emit('ATTACK_PLAYER', 'AIR_DEATH')
      }
    }
  }
}
